package com.cskaoyan.user.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.GateWayException;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.*;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IUserService;
import com.cskaoyan.user.service.IUserVerifyService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpCookie;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 * @Author: hogan
 * @Date: 2022/06/18/10:02
 * @Description: 用户模块
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    CaptchaController captchaController;
    @Autowired
    IUserService iUserService;
    @Autowired
    IUserVerifyService iUserVerifyService;
    @Autowired
    IKaptchaService kaptchaService;


    /**
     * @Description: 验证用户是否登录
     * @Author: hogan
     * @Date: 2022/6/18
     * @Time: 9:49
     */
    @GetMapping("/login")
    public ResponseData loginStatus(HttpServletRequest request) {
        String userInfo = (String) request.getHeader("user_info");
        if (userInfo == null) {
            throw new GateWayException(SysRetCodeConstants.GET_TOKEN_FAILED.getCode(),
                    SysRetCodeConstants.GET_TOKEN_FAILED.getMessage());
        }
        JSONObject object = JSON.parseObject(userInfo);
        long uid = Long.parseLong(object.get("uid").toString());
        String username = (String) object.get("username");
        UserLoginGetDto userLoginGetDto = new UserLoginGetDto();
        userLoginGetDto.setUsername(username);
        userLoginGetDto.setUid((int) uid);
        return new ResponseUtil<>().setData(userLoginGetDto);
    }

    @PostMapping("/register")
    @Transactional
    public ResponseData register(@RequestBody Map<String, String> map, HttpServletRequest httpServletRequest) {
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setUserName(map.get("userName"));
        userRegisterRequest.setUserPwd(map.get("userPwd"));
        userRegisterRequest.setEmail(map.get("email"));
        //验证码判断
/*        ResponseData responseData = captchaController.validKaptchaCode(map.get("captcha"), httpServletRequest);

        if (responseData.getCode() != 200) {
            return new ResponseUtil<>().setErrorMsg(Integer.parseInt(UserRetCode.KAPTCHA_CODE_ERROR.getCode()), UserRetCode.KAPTCHA_CODE_ERROR.getMessage());
        }

        UserRegisterResponse registerResponse = iUserService.register(userRegisterRequest);
        if (UserRetCode.SUCCESS.getCode().equals(registerResponse.getCode())) {
            return new ResponseUtil<>().setData(registerResponse, registerResponse.getMsg());
        }*/
        String kaptcha_uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setCode(map.get("captcha"));
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        String code = kaptchaCodeResponse.getCode();
        //判断验证码是否相同
        if (!code.equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }
        UserRegisterResponse registerResponse = iUserService.register(userRegisterRequest);
        if (!UserRetCode.SUCCESS.getCode().equals(registerResponse.getCode())) {
            return new ResponseUtil<>().setErrorMsg(registerResponse.getMsg());
        }
        // 调用成功
        ResponseData<Object> objectResponseData = new ResponseData<>();
        objectResponseData.setCode(200);
        objectResponseData.setMessage("注册成功");
        objectResponseData.setSuccess(true);
        return objectResponseData;
    }

    @PostMapping("/login")
    public ResponseData loginUser(@RequestBody Map map, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        UserLoginRequest request = new UserLoginRequest();
        request.setUserName(map.get("userName").toString());
        request.setPassword(map.get("userPwd").toString());
        String code = map.get("captcha").toString();
        //验证码判断
        ResponseData responseData = captchaController.validKaptchaCode(code, httpServletRequest);
        if (responseData.getCode() != 200) {
            return new ResponseUtil<>().setErrorMsg(Integer.parseInt(UserRetCode.KAPTCHA_CODE_ERROR.getCode()), UserRetCode.KAPTCHA_CODE_ERROR.getMessage());
        }

        UserLoginResponse response = iUserService.loginUser(request);
        if (UserRetCode.SUCCESS.getCode().equals(response.getCode())) {
            // 执行成功，直接返回前端需要的数据
            // 设置cookie
            Cookie cookie = CookieUtil.genCookie("access_token", response.getToken(), "/", 30 * 60);
            cookie.setHttpOnly(true);
            httpServletResponse.addCookie(cookie);
            return new ResponseUtil<>().setData(response, response.getMsg());
        }
        // 调用失败
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }


    @GetMapping("/loginOut")
    public ResponseData loginOut(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("access_token")) {
                cookies[i].setValue(null);
                cookies[i].setMaxAge(0);
                cookies[i].setPath("/");
                response.addCookie(cookies[i]);
            }
        }
        return new ResponseUtil<>().setData(null, "success");
    }

    @GetMapping("/verify")
    public ResponseData verify(String uid, String username) {
        UserVerifyRequest userVerifyRequest = new UserVerifyRequest();
        userVerifyRequest.setUserName(username);
        userVerifyRequest.setUuid(uid);
        UserVerifyResponse response = iUserVerifyService.updateVerify(userVerifyRequest);
        if (response.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response, "success");
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
}


